import React, { useEffect, useState } from 'react';
import {
  StyleSheet,
  Text,
  Modal as RNModal,
  TouchableHighlight,
} from 'react-native';
import {
  Badge,
  Button,
  Checkbox,
  Flex,
  Tabs,
  Toast,
  WingBlank,
  List,
} from '@ant-design/react-native';
import FlexTextField from '@/rcomponents/flexTextField';
import { LoadingContainer, Container } from '@/rcomponents/Container';
import { formatDate } from '@/helpers/dateutil';
import UserStore from '@/stores/userStore';
import Card from './components/responsiveCard';
import ReleaseJobStore from './releaseJobStore';
import JobReturnPage from './jobReturnPage';
import WorkerUserSelectPage from './workerUserSelectPage';
import FlightReleasePassPage from './flightReleasePassPage';
import DamageReportSubmitPage from './damageReport/damageSubmitPage';
import PDFView from 'react-native-view-pdf';

const styles = StyleSheet.create({
  pwCardTitle: {
    fontWeight: 'bold',
  },
  listHeader: {
    paddingVertical: 10,
    backgroundColor: '#dcdcdc',
    fontSize: 14,
    paddingLeft: 10,
  },
  cBox: { width: '50px', height: '50px' },
  fatherContainer: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    flexWrap: 'wrap',
    fontWeight: 'bold',
    width: 300,
    lineHeight: 30,
  },
});

function FleetDdCfStatus({ ddfcInfo, fleetMonitorInfo, acno }) {
  const rjStore = ReleaseJobStore.useStore();
  const userStore = UserStore.useStore();
  const [pdfModule, setPdfModule] = useState({
    ifShow: false,
    url: '',
  });
  const handleClose = () => {
    setPdfModule({ ...pdfModule, ifShow: false });
  };
  const handleViewCard = (item) => {
    setPdfModule({
      ...pdfModule,
      url: `http://testmrs.loongair.cn${item.jobCardUrl}`,
      ifShow: true,
    });
  };
  const handleLoadJob = async () => {
    if (acno) {
      const ddfcPara = {
        acno: acno,
        status: '1',
        menutype: '',
        desc: '',
        ddfcNo: '',
        ata: '',
      };
      const res = await rjStore.getDdFcAndFleetMonitor(
        userStore.user.LoginName,
        ddfcPara,
      );
      if (res.errorCode) {
        Toast.fail(res.errorMsg);
        return;
      }
    }
  };
  return (
    <LoadingContainer
      onRefresh={handleLoadJob}
      loading={rjStore.getDdFcAndFleetMonitor.loading}
      data={ddfcInfo}
      header={
        <Tabs
          tabs={[
            {
              title: 'DD/FC项目控制',
              text: (ddfcInfo || []).length,
            },
            { title: '机队状态实时监控' },
          ]}
        />
      }
      renderItem={({ item }) => (
        <List>
          <Card key={item.index}>
            <Card.Body>
              <Flex>
                <FlexTextField label="序号：" fieldValue={item.index} />
                <FlexTextField label="机号：" fieldValue={item.acno} />
              </Flex>
              <Flex>
                <FlexTextField label="状态：" fieldValue={item.status} />
                <FlexTextField label="版本：" fieldValue={item.version} />
              </Flex>
              <Flex>
                <FlexTextField label="ATA：" fieldValue={item.ata} />
                <FlexTextField label="保留编号：" fieldValue={item.ddfcNo} />
              </Flex>
              <Flex>
                <FlexTextField
                  label="故障发生时间："
                  fieldValue={formatDate(item.date, 'YYYY-MM-DD HH:mm')}
                />
              </Flex>
              <Flex>
                <FlexTextField
                  label="截止日期："
                  fieldValue={formatDate(item.limitTime, 'YYYY-MM-DD HH:mm')}
                />
              </Flex>

              <Flex>
                <FlexTextField
                  label="故障或缺陷描述："
                  fieldValue={item.description}
                />
              </Flex>
            </Card.Body>
            <Card.Footer
              key="footer"
              extra={
                item.jobCardUrl && (
                  <Button
                    size="small"
                    type="primary"
                    onPress={() => {
                      handleViewCard(item);
                    }}
                  >
                    查看附件
                  </Button>
                )
              }
            />
          </Card>
          <RNModal visible={pdfModule.ifShow} animationType="slide">
            <PDFView
              fadeInDuration={250.0}
              style={{ flex: 1 }}
              resource={pdfModule.url}
              resourceType={'url'}
              onLoad={() => console.log('PDF rendered from url')}
              onError={(error) => console.log('Cannot render PDF', error)}
            />
            <Button type="primary" onPress={handleClose}>
              关闭
            </Button>
          </RNModal>
          {/* <Card key={item.id}>
            <Card.Body>
              <Flex>
                <FlexTextField label="序号" fieldValue={item.release_by} />
                <FlexTextField label="机号" fieldValue={item.workers} />
              </Flex>
              <Flex>
                <FlexTextField
                  label="故障发生时间"
                  fieldValue={formatDate(
                    fleetMonitorInfo.est_depart_date,
                    'YYYY-MM-DD HH:mm',
                  )}
                />
              </Flex>
              <Flex>
                <FlexTextField
                  label="保留编号"
                  fieldValue={fleetMonitorInfo.statusDes}
                />
              </Flex>
              <Flex>
                <FlexTextField
                  label="版本"
                  fieldValue={fleetMonitorInfo.preflight}
                />
                <FlexTextField
                  label="ATA"
                  fieldValue={fleetMonitorInfo.airport}
                />
                <FlexTextField
                  label="故障或缺陷描述"
                  fieldValue={fleetMonitorInfo.postflight}
                />
              </Flex>
            </Card.Body>
          </Card> */}
        </List>
      )}
    />
  );
}

const FlightTaskList = [
  {
    title: '维修任务',
  },
  {
    key: 'tech',
    title: '技术状态',
  },
];
const MaintainTaskList = [
  {
    title: '航线工卡',
    key: 'taskCard',
  },
  {
    title: '例行任务',
    key: 'routineTasks',
  },
  {
    title: '非例行任务',
    key: 'unroutineTasks',
  },
];
function FlightReleaseJobPage({ navigation, route }) {
  const rjStore = ReleaseJobStore.useStore();
  const userStore = UserStore.useStore();
  const [disabled, setDisabled] = useState(false);
  const [checked, setChecked] = useState(false);
  useEffect(() => {
    handlePass();
    const unsubscribe = navigation.addListener('focus', () => {
      handleLoadJob();
    });
    return unsubscribe;
  }, [navigation]);
  const handleLoadJob = async () => {
    if (route.params) {
      const ddfcPara = {
        acno: route.params.acno,
        status: '1',
        menutype: '',
        desc: '',
        ddfcNo: '',
        ata: '',
      };
      await Promise.all([
        rjStore.getFlightPassDetail(
          userStore.user.LoginName,
          route.params.taskStageTid,
          route.params.flightTid,
        ),
        rjStore.getPassInfo(
          userStore.user.LoginName,
          route.params.taskStageTid,
          route.params.taskPaperType,
        ),
        rjStore.getDdFcAndFleetMonitor(userStore.user.LoginName, ddfcPara),
      ]);
    }
  };
  const renderFlightTaskTab = (tab) => {
    if (tab.key === 'tech') {
      return (
        <FleetDdCfStatus
          fleetMonitorInfo={rjStore.fleetMonitorInfo}
          ddfcInfo={rjStore.ddfcInfo}
          acno={route.params.acno}
        />
      );
    }
    return (
      <LoadingContainer
        onRefresh={handleLoadJob}
        loading={rjStore.getFlightPassDetail.loading}
        data={MaintainTaskList}
        renderItem={({ item, index }) => {
          const handleCheck = (itemId, eventchecked) => {
            rjStore.switchAssignCheck(index, itemId, eventchecked);
          };
          const scChildData = rjStore.flightPassDetail[index] || [];

          return (
            <List
              key={index}
              renderHeader={() => {
                return (
                  <Text style={styles.listHeader}>
                    {item.title} {scChildData.length}
                  </Text>
                );
              }}
            >
              {scChildData.map((maintainItem) => {
                return (
                  <TouchableHighlight
                    underlayColor="#CCC"
                    activeOpacity={0.5}
                    disabled={maintainItem.planStatusDes === '已关闭'}
                    onPress={() => {
                      setChecked(!checked);
                      handleCheck(maintainItem.id, checked);
                    }}
                    key={maintainItem.id}
                  >
                    <Card key={maintainItem.id}>
                      <Card.Header
                        title={
                          <Flex
                            style={styles.fatherContainer}
                            numberOfLines={10}
                          >
                            <Text style={styles.pwCardTitle}>
                              {maintainItem.cardTitle.replace(
                                /<\/?.+?\/?>/g,
                                '\n',
                              )}
                            </Text>
                          </Flex>
                        }
                        extra={
                          <Container float="right">
                            {maintainItem.planStatusDes !== '已关闭' && (
                              <Checkbox
                                checked={maintainItem.assignChecked}
                                onChange={(event) => {
                                  handleCheck(
                                    maintainItem.id,
                                    event.target.checked,
                                  );
                                  setChecked(!checked);
                                }}
                              />
                            )}
                          </Container>
                        }
                      />
                      <Card.Body>
                        <Flex>
                          <FlexTextField
                            label="指令号"
                            fieldValue={maintainItem.workOrder}
                          />
                          <FlexTextField
                            label="状态"
                            fieldValue={maintainItem.planStatusDes}
                          />
                        </Flex>
                        <Flex>
                          <FlexTextField
                            label="计划"
                            fieldValue={formatDate(
                              maintainItem.planDate,
                              'YYYY-MM-DD HH:mm',
                            )}
                          />
                          <FlexTextField
                            label="完工"
                            fieldValue={formatDate(
                              maintainItem.finishDate,
                              'YYYY-MM-DD HH:mm',
                            )}
                          />
                        </Flex>
                        <Flex>
                          <FlexTextField
                            label="工作者"
                            fieldValue={maintainItem.workPer}
                            wrap="nowrap"
                          />
                        </Flex>
                        <Flex>
                          <FlexTextField
                            label="工卡号"
                            fieldValue={maintainItem.jobCard}
                          />
                        </Flex>
                      </Card.Body>
                      <Card.Footer
                        extra={
                          <Container float="right">
                            {maintainItem.planStatusDes !== '已关闭' && (
                              <Flex>
                                {maintainItem.planStatus !== '11' &&
                                  maintainItem.planStatus !== '13' && (
                                    <WingBlank>
                                      <Button
                                        type="ghost"
                                        size="small"
                                        onPress={() =>
                                          handleTaskReturn(maintainItem)
                                        }
                                      >
                                        退单
                                      </Button>
                                    </WingBlank>
                                  )}
                                {maintainItem.planStatus !== '11' &&
                                  maintainItem.planStatus !== '13' && (
                                    <Button
                                      type="ghost"
                                      size="small"
                                      onPress={() =>
                                        handleSubimtDamage(maintainItem)
                                      }
                                    >
                                      结构损伤报告
                                    </Button>
                                  )}
                              </Flex>
                            )}
                          </Container>
                        }
                      />
                    </Card>
                  </TouchableHighlight>
                );
              })}
            </List>
          );
        }}
      />
    );
  };
  const handleSubimtDamage = (item) => {
    navigation.navigate(DamageReportSubmitPage.routeName, {
      acno: route.params.acno,
      airport: route.params.airport,
      jobCard: item.jobCard,
    });
  };
  const handleTaskReturn = (item) => {
    navigation.navigate(JobReturnPage.routeName, {
      taskTid: item.id,
      taskStageTid: route.params.taskStageTid,
      flightTid: route.params.flightTid,
    });
  };
  const handleAssignRepairerCancel = () => {
    rjStore.cancelAssignRepairer();
  };
  const handleAssignRepairer = () => {
    const taskIds = rjStore.flightPassDetail
      .map((fpd) =>
        fpd.filter((fpdd) => fpdd.assignChecked).map((fpdd) => fpdd.id),
      )
      .reduce((cur, acc) => cur.concat(acc), []);
    navigation.navigate(WorkerUserSelectPage.routeName, {
      title: '派工',
      type: '2',
      acno: route.params.acno,
      ifMain: '1', //派技术员
      taskStageTid: route.params.taskStageTid,
      flightTid: route.params.flightTid,
      taskTid: taskIds,
    });

    rjStore.cancelAssignRepairer();
  };
  const handleJobPass = () => {
    navigation.navigate(FlightReleasePassPage.routeName, {
      taskStageTid: route.params.taskStageTid,
      flightTid: route.params.flightTid,
      taskPaperType: route.params.taskPaperType,
    });
  };

  const handlePass = async () => {
    const paraVerify = await rjStore.verifyPass(
      userStore.user.LoginName,
      route.params.taskStageTid,
      route.params.flightTid,
    );
    if (paraVerify.data !== true) {
      setDisabled(true);
    }
  };

  return (
    <>
      <Tabs
        tabs={FlightTaskList.map((scc, index) => ({
          key: scc.key,
          title: (
            <Badge
              text={
                index === 0
                  ? (rjStore.flightPassDetail[0] || []).length +
                    (rjStore.flightPassDetail[1] || []).length +
                    (rjStore.flightPassDetail[2] || []).length
                  : (rjStore.ddfcInfo || []).length
              }
              key={scc.title}
            >
              <Text>{scc.title}</Text>
            </Badge>
          ),
        }))}
      >
        {renderFlightTaskTab}
      </Tabs>
      {rjStore.flightPassDetail.filter(
        (fpd) => fpd.filter((fpdi) => fpdi.assignChecked).length,
      ).length ? (
        <Flex>
          <Flex.Item flex={1}>
            <Button type="ghost" onPress={handleAssignRepairerCancel}>
              取消
            </Button>
          </Flex.Item>
          <Flex.Item flex={2}>
            <Button type="primary" onPress={handleAssignRepairer}>
              派工
            </Button>
          </Flex.Item>
        </Flex>
      ) : (
        <Button type="primary" onPress={handleJobPass}>
          {rjStore.flightPassInfo ? '放行信息' : '放行确认'}
        </Button>
      )}
    </>
  );
}

FlightReleaseJobPage.routeName = 'FlightReleaseJob';
FlightReleaseJobPage.permission = 'RFlightReleaseJob';
export default FlightReleaseJobPage;
